package com.zuo_book.controller;

import com.zuo_book.common.Result;
import com.zuo_book.common.ResultCode;
import com.zuo_book.dto.UserInfoDTO;
import com.zuo_book.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    /**
     * 获取当前用户信息
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoDTO> getCurrentUserInfo() {
        UserInfoDTO userInfo = userService.getCurrentUserInfo();
        return Result.success(userInfo);
    }

    /**
     * 获取指定用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/{userId}")
    public Result<UserInfoDTO> getUserInfo(@PathVariable Long userId) {
        UserInfoDTO userInfo = userService.getUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 更新用户信息
     * @param userInfoDTO 用户信息
     * @return 结果
     */
    @PutMapping("/info")
    public Result<Void> updateUserInfo(@Valid @RequestBody UserInfoDTO userInfoDTO) {
        userService.updateUserInfo(userInfoDTO);
        return Result.success("更新成功");
    }

    /**
     * 上传头像
     * @param file 头像文件
     * @return 包含头像URL的响应
     */
    @PostMapping("/avatar")
    public Result<Object> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.failure(ResultCode.FAILED,"头像文件不能为空");
            }

            String avatarUrl = userService.uploadAvatar(file);
            System.out.println("头像上传成功，URL: " + avatarUrl);

            // 返回包含URL的对象
            return Result.success(new java.util.HashMap<String, String>() {{
                put("url", avatarUrl);
            }});
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(ResultCode.FAILED,"头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 结果
     */
    @PostMapping("/change-password")
    public Result<Void> changePassword(
            @RequestParam @NotBlank(message = "旧密码不能为空") String oldPassword,
            @RequestParam @NotBlank(message = "新密码不能为空") String newPassword) {
        userService.changePassword(oldPassword, newPassword);
        return Result.success("密码修改成功");
    }

    /**
     * 查询用户id是否存在
     */
    @GetMapping("/check-user-id/{userId}")
    public Result<Boolean> checkUserId(@PathVariable Long userId) {
        boolean exists = userService.checkUserId(userId);
        return Result.success(exists);
    }
}
